/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.threads;

import aso.upna.controllers.SendInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author triki
 */
public class UdpSenderThread implements Runnable {

    private String filename;
    private SendInfo info;
    private byte[] aux = null;
    private InetAddress ip;
    private int remotePort;

    public UdpSenderThread(String filename,SendInfo info,InetAddress ip,int port,int pack_size)
    {
        this.filename = new String(filename);
        this.info = info;
        aux = new byte[pack_size];
        this.ip = ip;
        remotePort = port;
    }

    public void run()
    {
        FileInputStream ifile = null;
        DatagramPacket dPack;

        try
        {
            System.out.println("Opening UDP socket..");
            DatagramSocket dgram = new DatagramSocket();
            File f = new File(filename);
            ifile = new FileInputStream(filename);
            int size = 0;

            info.setTotal(f.length());
            info.setEnviado(size);

            while (ifile.read(aux) > -1)
            {
                try
                {
                    dPack = new DatagramPacket(aux, 2048, ip, remotePort);
                    dgram.send(dPack);
                    size += 2048;
                    info.setEnviado(size);
                    //Esperamos 50ms para no saturar el socket de recepcion
                    Thread.sleep(50);
                }
                catch (InterruptedException ex)
                {
                    //ex.printStackTrace();
                    break;
                }
            }
            dgram.close();
        }
        catch (IOException ex)
        {
            Logger.getLogger(UdpSenderThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            try
            {
                ifile.close();
            }
            catch (IOException ex)
            {
                Logger.getLogger(UdpSenderThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}
